package com.topteam.component.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.topteam.frame.controllor.BaseController;
import com.topteam.utility.StringUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class TopCheckBoxGroup extends TopTemplateModel{

	public final static String TAG = "checkboxgroup";
	
	
	private String id;
	
	private String name;
	
	private String url;
	
	private BaseController bc;
	
	public TopCheckBoxGroup(BaseController bc){
		this.bc = bc;
	}
	
	private void initPara(Map para, Environment env) throws TemplateException{
		id = getStrPara("id", para, env);
		if(StringUtil.isNull(id)){
			throw new TemplateException("必须直接按钮id的值", env);
		}
		url = getStrPara("url", para, env);
		name = getStrPara("name", para, env);
	}
	
	@Override
	public void execute(Environment env, Map params, TemplateModel[] arg2,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		initPara(params, env);
		Writer w = env.getOut();
		w.write("<div id='"+id+"' >" );
		w.write("</div>");
		
		writeScript(w);
	}

	private void writeScript(Writer w) throws IOException{
		w.write("<script type=\"text/javascript\">");
		w.write("$(function(){ \r\n");
		w.write("   $.ajax({ \r\n");
		w.write("		url:\""+url+"\", \r\n");
		w.write("		type:\"GET\", \r\n");
		w.write("		dataType:\"JSON\", \r\n");
		w.write("		success:function(data){ \r\n");
		w.write("			for(var s in data){ \r\n");
		w.write("				$(\"#"+id+"\").append('<input type=\"checkbox\" '+(data[s].selected?'checked':'')+' value=\"'+data[s].value+'\" name=\""+name+"\" />'+data[s].text  );\r\n");
		w.write("			}\r\n");
		w.write("		} \r\n");
		w.write("	}); \r\n");
		w.write("	});"); 
		w.write("</script>");
	}
}
